<template>
  <div class="articles-page">
    <!-- 页面头部 -->
    <section class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <Breadcrumb
          :items="[
            { path: '/community', title: '社区首页' },
            { path: '', title: '优秀文章' },
          ]"
        />
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
            优秀文章
          </h1>
          <div class="header-actions flex items-center gap-4">
            <el-button
              type="primary"
              :icon="Document"
              @click="$router.push('/user/articles')"
            >
              我发表的文章
            </el-button>
            <el-button
              type="primary"
              :icon="Edit"
              @click="showSubmitForm = true"
            >
              投稿
            </el-button>
          </div>
        </div>
      </div>
    </section>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="articles-content flex gap-6">
        <!-- 左侧内容区 -->
        <div class="main-content flex-1">
          <!-- 筛选栏 -->
          <div
            class="filter-bar bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6"
          >
            <div class="flex items-center gap-4">
              <el-select
                v-model="filterConditions.sortBy"
                placeholder="排序方式"
                class="w-48"
              >
                <el-option
                  v-for="option in sortOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <el-select
                v-model="filterConditions.status"
                placeholder="文章状态"
                class="w-48"
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <el-input
                v-model="searchQuery"
                placeholder="搜索文章"
                class="w-96"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 文章列表 -->
          <div class="articles-list" v-loading="loading">
            <div
              v-for="article in articlesList"
              :key="article.id"
              class="article-card bg-white dark:bg-gray-800 rounded-lg shadow-sm mb-6 overflow-hidden hover:shadow-lg transition-all duration-300 cursor-pointer group"
              @click="handleArticleClick(article)"
            >
              <div class="flex">
                <!-- 文章封面图 -->
                <div
                  class="article-cover w-64 h-48 flex-shrink-0 overflow-hidden"
                >
                  <el-image
                    :src="article.cover"
                    fit="cover"
                    class="w-full h-full group-hover:scale-110 transition-transform duration-500"
                  />
                </div>
                <!-- 文章内容 -->
                <div
                  class="article-content flex-1 p-6 flex flex-col justify-between"
                >
                  <div>
                    <h3
                      class="text-xl font-bold text-gray-900 dark:text-white mb-2 line-clamp-1 group-hover:text-primary-500 dark:group-hover:text-primary-400 transition-colors duration-300"
                    >
                      {{ article.title }}
                    </h3>
                    <p
                      class="text-gray-600 dark:text-gray-400 mb-4 line-clamp-2 text-sm leading-relaxed"
                    >
                      {{ article.description }}
                    </p>
                  </div>
                  <div
                    class="article-meta flex items-center text-sm text-gray-500 dark:text-gray-400"
                  >
                    <div class="flex items-center flex-1">
                      <el-avatar
                        :size="28"
                        :src="article.author.avatar"
                        class="mr-2 ring-2 ring-offset-2 ring-gray-100 dark:ring-gray-700"
                      />
                      <span class="mr-4 font-medium">{{
                        article.author.nickname
                      }}</span>
                      <div class="flex items-center space-x-4">
                        <span class="flex items-center">
                          <el-icon class="mr-1"><View /></el-icon>
                          {{ article.viewCount }}
                        </span>
                        <span class="flex items-center">
                          <el-icon class="mr-1"><Star /></el-icon>
                          {{ article.likeCount }}
                        </span>
                        <span class="flex items-center">
                          {{ formatTime(article.createTime) }}
                        </span>
                      </div>
                    </div>
                    <el-tag
                      v-if="article.status !== 'published'"
                      :type="getStatusType(article.status)"
                      size="small"
                      class="ml-4"
                      effect="light"
                    >
                      {{ getStatusLabel(article.status) }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && !articlesList.length"
              description="暂无相关文章"
            >
              <el-button type="primary" @click="showSubmitForm = true">
                立即投稿
              </el-button>
            </el-empty>

            <!-- 分页 -->
            <div
              v-if="total > 0"
              class="pagination-wrapper flex justify-center mt-8"
            >
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar w-80 flex-shrink-0">
          <!-- 投稿指南 -->
          <div
            class="guide-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">
              投稿指南
            </h3>
            <ul class="text-gray-600 dark:text-gray-400 space-y-2">
              <li>文章内容需要原创，不得抄袭</li>
              <li>图片需要清晰，大小不超过5MB</li>
              <li>标题简洁明了，20字以内</li>
              <li>正文内容详实，不少于300字</li>
              <li>审核通过后将在首页展示</li>
            </ul>
          </div>

          <!-- 热门标签 -->
          <div
            class="tags-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">
              热门标签
            </h3>
            <div class="tags-cloud flex flex-wrap gap-2">
              <el-tag
                v-for="tag in hotTags"
                :key="tag.id"
                :type="tag.type"
                class="cursor-pointer"
                @click="handleTagClick(tag)"
              >
                {{ tag.name }}
                <span class="ml-1 text-xs">{{ tag.count }}</span>
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 投稿表单弹窗 -->
    <el-dialog
      v-model="showSubmitForm"
      title="文章投稿"
      width="1000px"
      :close-on-click-modal="false"
      destroy-on-close
      class="submit-dialog"
    >
      <el-form
        ref="submitFormRef"
        :model="submitForm"
        :rules="submitRules"
        label-width="80px"
        class="submit-form"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <!-- 基本信息部分 -->
            <div class="form-section">
              <h3 class="section-title">基本信息</h3>
              <el-form-item label="标题" prop="title">
                <el-input
                  v-model="submitForm.title"
                  placeholder="请输入文章标题（50字以内）"
                  :maxlength="50"
                  show-word-limit
                />
              </el-form-item>

              <el-form-item label="分类" prop="category">
                <el-select
                  v-model="submitForm.category"
                  placeholder="请选择文章分类"
                  class="w-full"
                >
                  <el-option
                    v-for="option in categoryOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="标签" prop="tags">
                <el-select
                  v-model="submitForm.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入标签（最多5个）"
                  class="w-full"
                >
                  <el-option
                    v-for="tag in hotTags"
                    :key="tag.id"
                    :label="tag.name"
                    :value="tag.id"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="摘要" prop="summary">
                <el-input
                  v-model="submitForm.summary"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入文章摘要（200字以内）"
                  :maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </div>

            <!-- 文章内容部分 -->
            <div class="form-section">
              <h3 class="section-title">文章内容</h3>
              <el-form-item prop="content" class="mb-0">
                <div class="editor-container">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editor"
                    :defaultConfig="toolbarConfig"
                    mode="default"
                    class="editor-toolbar"
                  />
                  <Editor
                    style="height: 400px; overflow-y: hidden"
                    v-model="submitForm.content"
                    :defaultConfig="editorConfig"
                    mode="default"
                    @onCreated="handleEditorCreated"
                    class="editor-content"
                  />
                </div>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="8">
            <!-- 封面图片部分 -->
            <div class="form-section">
              <h3 class="section-title">封面图片</h3>
              <el-form-item prop="cover">
                <el-upload
                  class="cover-uploader"
                  :action="uploadAction"
                  :show-file-list="false"
                  :on-success="handleCoverSuccess"
                  :before-upload="beforeCoverUpload"
                  :on-error="handleUploadError"
                >
                  <div class="upload-area">
                    <el-image
                      v-if="submitForm.cover"
                      :src="submitForm.cover"
                      fit="cover"
                      class="w-full h-48 rounded"
                    />
                    <div v-else class="upload-placeholder">
                      <el-icon :size="24"><Plus /></el-icon>
                      <div class="mt-2">点击上传封面图</div>
                      <div class="text-xs text-gray-400 mt-1">
                        建议尺寸：800x600px
                      </div>
                    </div>
                  </div>
                </el-upload>
              </el-form-item>
            </div>

            <!-- 附件上传部分 -->
            <div class="form-section">
              <h3 class="section-title">附件上传</h3>
              <el-upload
                class="attachment-uploader"
                :action="uploadAction"
                :on-success="handleAttachmentSuccess"
                :before-upload="beforeAttachmentUpload"
                :on-remove="handleAttachmentRemove"
                :on-error="handleUploadError"
                multiple
              >
                <el-button type="primary" plain>
                  <el-icon><Upload /></el-icon>
                  <span>上传附件</span>
                </el-button>
                <template #tip>
                  <div class="text-xs text-gray-400 mt-1">
                    支持常见文档格式，单个文件不超过10MB
                  </div>
                </template>
              </el-upload>
            </div>

            <!-- 发布选项部分 -->
            <div class="form-section">
              <h3 class="section-title">发布选项</h3>
              <div class="space-y-4">
                <el-form-item label="原创声明" class="mb-0">
                  <el-switch
                    v-model="submitForm.isOriginal"
                    active-text="原创"
                    inactive-text="转载"
                  />
                </el-form-item>

                <el-form-item
                  v-if="!submitForm.isOriginal"
                  label="原文链接"
                  prop="sourceUrl"
                >
                  <el-input
                    v-model="submitForm.sourceUrl"
                    placeholder="请输入原文链接"
                  />
                </el-form-item>

                <el-form-item label="评论设置" class="mb-0">
                  <el-switch
                    v-model="submitForm.allowComment"
                    active-text="允许评论"
                    inactive-text="禁止评论"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-500">
            提交后需要等待管理员审核，请耐心等待
          </div>
          <div class="space-x-2">
            <el-button @click="showSubmitForm = false">取消</el-button>
            <el-button
              type="primary"
              :loading="submitting"
              @click="handleSubmit"
            >
              提交审核
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  watch,
  onBeforeUnmount,
  shallowRef,
  computed,
} from "vue";
import { ElMessage } from "element-plus";
import {
  Edit,
  Search,
  View,
  Star,
  Plus,
  Upload,
  Document,
} from "@element-plus/icons-vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import { useRouter } from "vue-router";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import service from "@/api/axios"; // 导入axios实例

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

// 页面状态
const loading = ref(false);
const submitting = ref(false);
const showSubmitForm = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchQuery = ref("");

// 筛选条件
const filterConditions = reactive({
  sortBy: "newest",
  status: "",
  tags: [],
});

// 排序选项
const sortOptions = [
  { label: "最新发布", value: "newest" },
  { label: "最多浏览", value: "most_viewed" },
  { label: "最多点赞", value: "most_liked" },
];

// 状态选项
const statusOptions = [
  { label: "全部", value: "" },
  { label: "已发布", value: "published" },
  { label: "审核中", value: "pending" },
  { label: "未通过", value: "rejected" },
];

// 文章列表
const allArticles = ref([]); // 存储所有从API获取的文章
const filteredArticles = computed(() => {
  // 从所有文章中筛选、排序
  let result = [...allArticles.value];
  
  // 1. 应用搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(article => 
      article.title?.toLowerCase().includes(query) || 
      article.description?.toLowerCase().includes(query)
    );
  }
  
  // 2. 应用状态过滤
  if (filterConditions.status) {
    result = result.filter(article => article.status === filterConditions.status);
  }
  
  // 3. 应用标签过滤
  if (filterConditions.tags && filterConditions.tags.length > 0) {
    result = result.filter(article => {
      if (!article.tags) return false;
      return filterConditions.tags.some(tagId => 
        article.tags.some(tag => tag.id === tagId)
      );
    });
  }
  
  // 4. 应用排序
  switch (filterConditions.sortBy) {
    case "newest":
      result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
      break;
    case "most_viewed":
      result.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));
      break;
    case "most_liked":
      result.sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0));
      break;
  }
  
  return result;
});

// 分页后的文章列表
const articlesList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredArticles.value.slice(start, end);
});

// 自动更新总数
watch(filteredArticles, (newVal) => {
  total.value = newVal.length;
}, { immediate: true });

// 热门标签
const hotTags = ref([
  { id: 1, name: "美食", count: 128, type: "" },
  { id: 2, name: "景点", count: 98, type: "success" },
  { id: 3, name: "文化", count: 76, type: "warning" },
  { id: 4, name: "摄影", count: 54, type: "danger" },
]);

// 投稿表单
const submitFormRef = ref(null);
const submitForm = reactive({
  title: "",
  cover: "",
  content: "",
  summary: "",
  tags: [],
  category: "",
  isOriginal: true,
  sourceUrl: "",
  allowComment: true,
  attachments: [],
});

// 表单校验规则
const submitRules = {
  title: [
    { required: true, message: "请输入文章标题", trigger: "blur" },
    { max: 50, message: "标题不能超过50个字", trigger: "blur" },
  ],
  cover: [{ required: true, message: "请上传文章封面", trigger: "change" }],
  content: [
    { required: true, message: "请输入文章内容", trigger: "blur" },
    { min: 300, message: "内容不能少于300字", trigger: "blur" },
  ],
  summary: [
    { required: true, message: "请输入文章摘要", trigger: "blur" },
    { max: 200, message: "摘要不能超过200个字", trigger: "blur" },
  ],
  tags: [
    { required: true, message: "请选择文章标签", trigger: "change" },
    { type: "array", max: 5, message: "最多选择5个标签", trigger: "change" },
  ],
  category: [{ required: true, message: "请选择文章分类", trigger: "change" }],
};

// 上传配置 - 修复linter错误，将其放在setup顶层
const uploadAction = "/api/upload"; // 替换为实际的上传接口

const router = useRouter();

// 获取文章列表
const getArticlesList = async () => {
  loading.value = true;
  try {
    // 调用API获取所有文章
    const response = await service.get("/public/articles");
    
    // 处理API响应
    if (response && response.data && Array.isArray(response.data)) {
      allArticles.value = response.data;
    } else {
      // 使用测试数据作为后备
      allArticles.value = [
        {
          id: 1,
          title: "贵港古镇探秘之旅",
          description:
            "走进贵港古镇，感受千年历史文化的积淀，品味独特的建筑风格...",
          cover: "/images/articles/ancient-town.jpg",
          author: {
            avatar: "/images/avatar/user1.jpg",
            nickname: "文化记录者",
          },
          viewCount: 1234,
          likeCount: 321,
          createTime: "2024-03-15 10:00:00",
          status: "published",
          tags: [{ id: 2, name: "景点" }, { id: 3, name: "文化" }],
        },
        {
          id: 2,
          title: "贵港美食之旅：寻味八桂名城",
          description:
            "贵港作为广西的重要城市，拥有丰富多样的美食文化...",
          cover: "/images/articles/food.jpg",
          author: {
            avatar: "/images/avatar/user2.jpg",
            nickname: "美食达人",
          },
          viewCount: 986,
          likeCount: 245,
          createTime: "2024-03-10 14:30:00",
          status: "published",
          tags: [{ id: 1, name: "美食" }],
        },
        {
          id: 3,
          title: "贵港摄影指南：拍出最美的城市风光",
          description:
            "贵港风景秀丽，处处是景。本文为摄影爱好者提供拍摄贵港美景的技巧和地点推荐...",
          cover: "/images/articles/photography.jpg",
          author: {
            avatar: "/images/avatar/user3.jpg",
            nickname: "摄影师阿强",
          },
          viewCount: 756,
          likeCount: 189,
          createTime: "2024-03-05 09:15:00",
          status: "published",
          tags: [{ id: 4, name: "摄影" }],
        },
      ];
    }
  } catch (error) {
    console.error("获取文章列表失败:", error);
    
    // 使用测试数据作为后备
    allArticles.value = [
      {
        id: 1,
        title: "贵港古镇探秘之旅",
        description:
          "走进贵港古镇，感受千年历史文化的积淀，品味独特的建筑风格...",
        cover: "/images/articles/ancient-town.jpg",
        author: {
          avatar: "/images/avatar/user1.jpg",
          nickname: "文化记录者",
        },
        viewCount: 1234,
        likeCount: 321,
        createTime: "2024-03-15 10:00:00",
        status: "published",
        tags: [{ id: 2, name: "景点" }, { id: 3, name: "文化" }],
      },
      {
        id: 2,
        title: "贵港美食之旅：寻味八桂名城",
        description:
          "贵港作为广西的重要城市，拥有丰富多样的美食文化...",
        cover: "/images/articles/food.jpg",
        author: {
          avatar: "/images/avatar/user2.jpg",
          nickname: "美食达人",
        },
        viewCount: 986,
        likeCount: 245,
        createTime: "2024-03-10 14:30:00",
        status: "published",
        tags: [{ id: 1, name: "美食" }],
      },
    ];
  } finally {
    loading.value = false;
  }
};

// 处理标签点击
const handleTagClick = (tag) => {
  filterConditions.tags = [tag.id];
  currentPage.value = 1;
};

// 处理封面上传成功
const handleCoverSuccess = (res) => {
  if (res && res.data && res.data.url) {
    submitForm.cover = res.data.url;
  } else {
    ElMessage.warning("封面上传成功，但未获取到图片URL");
  }
};

// 上传前检查
const beforeCoverUpload = (file) => {
  const isImage = /^image\//.test(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB！");
    return false;
  }
  return true;
};

// 修改编辑器相关的状态声明
const editor = shallowRef(null);
const editorRef = shallowRef(null);

// 编辑器配置
const editorConfig = {
  placeholder: "请输入文章内容...",
  autoFocus: false,
  scroll: true,
  MENU_CONF: {
    uploadImage: {
      server: "/api/upload/image",
      fieldName: "file",
      maxFileSize: 5 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ["image/*"],
      metaWithUrl: true,
      customInsert(res, insertFn) {
        insertFn(res.url, res.alt, res.href);
      },
    },
  },
};

// 工具栏配置
const toolbarConfig = {
  toolbarKeys: [
    "headerSelect",
    "|",
    "bold",
    "italic",
    "underline",
    "through",
    "|",
    "bulletedList",
    "numberedList",
    "|",
    "uploadImage",
    "|",
    "blockquote",
    "|",
    "undo",
    "redo",
  ],
};

// 处理编辑器创建
const handleEditorCreated = (e) => {
  editor.value = e;
};

// 处理上传错误
const handleUploadError = (error) => {
  ElMessage.error("上传失败：" + (error.message || "未知错误"));
};

// 处理附件上传成功
const handleAttachmentSuccess = (res) => {
  if (res && res.data) {
    submitForm.attachments.push({
      name: res.data.originalName || res.data.name,
      url: res.data.url,
      size: res.data.size,
    });
    ElMessage.success("附件上传成功");
  } else {
    ElMessage.warning("附件上传成功，但未获取到完整信息");
  }
};

// 处理附件上传前的检查
const beforeAttachmentUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error("附件大小不能超过 10MB！");
    return false;
  }
  return true;
};

// 处理附件移除
const handleAttachmentRemove = (file) => {
  const index = submitForm.attachments.findIndex(
    (item) => item.url === file.url,
  );
  if (index > -1) {
    submitForm.attachments.splice(index, 1);
  }
};

// 修改提交处理函数
const handleSubmit = async () => {
  if (!submitFormRef.value) return;

  await submitFormRef.value.validate(async (valid) => {
    if (valid) {
      if (submitForm.content.length < 300) {
        ElMessage.warning("文章内容不能少于300字");
        return;
      }

      submitting.value = true;
      try {
        // 构建提交数据
        const postData = {
          ...submitForm,
          content: submitForm.content,
          wordCount: submitForm.content.length,
          createTime: new Date().toISOString(),
        };

        // 调用投稿API
        const response = await service.post("/articles/submit", postData);
        
        if (response && response.data && response.data.success) {
          ElMessage.success("投稿成功，请等待审核");
          showSubmitForm.value = false;
          resetForm();
          getArticlesList();
        } else {
          ElMessage.warning("投稿可能未成功，请稍后查看您的投稿列表");
        }
      } catch (error) {
        console.error("投稿失败:", error);
        ElMessage.error("投稿失败：" + (error.message || "未知错误"));
      } finally {
        submitting.value = false;
      }
    }
  });
};

// 修改重置表单函数
const resetForm = () => {
  submitForm.title = "";
  submitForm.cover = "";
  submitForm.content = "";
  submitForm.summary = "";
  submitForm.tags = [];
  submitForm.category = "";
  submitForm.isOriginal = true;
  submitForm.sourceUrl = "";
  submitForm.allowComment = true;
  submitForm.attachments = [];

  if (submitFormRef.value) {
    submitFormRef.value.resetFields();
  }
  if (editor.value) {
    editor.value.setHtml("");
  }
};

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    published: "success",
    pending: "warning",
    rejected: "danger",
  };
  return types[status] || "info";
};

// 获取状态标签
const getStatusLabel = (status) => {
  const labels = {
    published: "已发布",
    pending: "审核中",
    rejected: "未通过",
  };
  return labels[status] || status;
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 监听搜索输入
watch(searchQuery, () => {
  currentPage.value = 1;
});

// 监听筛选条件变化
watch(
  filterConditions,
  () => {
    currentPage.value = 1;
  },
  { deep: true },
);

// 处理文章点击
const handleArticleClick = (article) => {
  router.push(`/community/article/${article.id}`);
};

// 添加文章分类选项
const categoryOptions = [
  { label: "景点游记", value: "spots" },
  { label: "美食推荐", value: "food" },
  { label: "文化探索", value: "culture" },
  { label: "活动报道", value: "event" },
  { label: "攻略指南", value: "guide" },
];

// 加载热门标签
const getHotTags = async () => {
  try {
    const response = await service.get("/public/articles/hot-tags");
    if (response && response.data && Array.isArray(response.data)) {
      hotTags.value = response.data;
    }
  } catch (error) {
    console.error("获取热门标签失败:", error);
    // 使用测试数据，已经在上面定义
  }
};

onMounted(() => {
  getArticlesList();
  getHotTags();
});

// 修改组件卸载时的清理
onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
  }
});
</script>

<style lang="scss" scoped>
.articles-page {
  .cover-uploader {
    :deep(.el-upload) {
      @apply w-full;
    }
  }

  .article-card {
    @apply border border-gray-100 dark:border-gray-700;

    &:hover {
      @apply border-primary-100 dark:border-primary-900;
    }

    .article-cover {
      @apply relative;

      &::after {
        content: "";
        @apply absolute inset-0 bg-black/5 dark:bg-black/20 opacity-0 transition-opacity duration-300;
      }
    }

    &:hover {
      .article-cover::after {
        @apply opacity-100;
      }
    }

    .article-meta {
      .el-icon {
        @apply text-gray-400 dark:text-gray-500;
      }
    }
  }

  .card-header {
    @apply flex items-center justify-between;

    .header-actions {
      @apply flex items-center gap-4;
    }
  }
}

.submit-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .submit-form {
    .form-section {
      @apply bg-white dark:bg-gray-800 rounded-lg p-4 mb-6;

      .section-title {
        @apply text-lg font-bold mb-4 text-gray-900 dark:text-white;
      }
    }

    .editor-container {
      @apply border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden;

      .editor-toolbar {
        @apply border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800;
      }

      .editor-content {
        @apply bg-white dark:bg-gray-800;
      }

      :deep(.w-e-text-container) {
        @apply bg-white dark:bg-gray-800;

        [data-slate-editor] {
          @apply text-gray-900 dark:text-gray-100;
        }
      }

      :deep(.w-e-toolbar) {
        @apply bg-white dark:bg-gray-800;
      }

      :deep(.w-e-bar-item) {
        @apply text-gray-700 dark:text-gray-300;

        &:hover {
          @apply bg-gray-100 dark:bg-gray-700;
        }

        .w-e-icon {
          @apply text-gray-700 dark:text-gray-300;
        }
      }

      :deep(.w-e-bar-divider) {
        @apply bg-gray-200 dark:bg-gray-700;
      }

      :deep(.w-e-bar-item-active) {
        @apply bg-primary-50 dark:bg-primary-900;
      }

      :deep(.w-e-text-placeholder) {
        @apply text-gray-400 dark:text-gray-500;
      }

      :deep(.w-e-panel-content-color) {
        @apply bg-white dark:bg-gray-800;
      }

      :deep(.w-e-panel) {
        @apply bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700;

        .w-e-panel-tab-title {
          @apply text-gray-900 dark:text-gray-100;
        }

        .w-e-panel-tab-content {
          @apply text-gray-900 dark:text-gray-100;
        }
      }
    }

    .upload-area {
      @apply border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-lg 
             hover:border-primary-500 dark:hover:border-primary-500 
             transition-colors duration-300 cursor-pointer;

      .upload-placeholder {
        @apply h-48 flex flex-col items-center justify-center text-gray-400;
      }
    }

    .attachment-uploader {
      :deep(.el-upload-list) {
        @apply mt-4;
      }
    }
  }
}
</style>
